﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Documents;
using System.Windows;
using System.Collections.Specialized;
using System.Windows.Media;
using System.Windows.Media;
using System.ComponentModel;

namespace ZOIL.Library.Behaviors
{
    public class SelectionView : Adorner
    {

        private Brush _fillBrush = new SolidColorBrush(Color.FromArgb(55, 0, 100, 0));
        private Pen _strokePen = new Pen(Brushes.Black, 1);

        public SelectionView(UIElement adornedElement, Selection selection, SelectionModes selectionMode) : base(adornedElement)
        {
            Selection = selection;
            SelectionMode = selectionMode;

            if (SelectionMode == SelectionModes.BoundingBox)
            {
                selection.SelectionGeometry = new RectangleGeometry(new Rect(Selection.Points.Last(), Selection.Points.Last()));
            }
            else
            {
                var startFigure = new PathFigure
                                      {
                                          StartPoint = Selection.Points.Last()
                                      };
                selection.SelectionGeometry = new PathGeometry(new[]{startFigure});
            }
            Selection.Points.CollectionChanged += OnPointCollectionChanged;

            Unloaded += OnUnloaded;
        }

        private void OnUnloaded(object sender, RoutedEventArgs e)
        {
            Selection.Points.CollectionChanged -= OnPointCollectionChanged;
        }

        public Selection Selection { get; private set; }

        public SelectionModes SelectionMode { get; private set; }

        private void OnPointCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (SelectionMode == SelectionModes.BoundingBox)
            {
                (Selection.SelectionGeometry as RectangleGeometry).Rect = new Rect(Selection.Points.First(), Selection.Points.Last());
            }
            else
            {
                (Selection.SelectionGeometry as PathGeometry).Figures.First().Segments.Add(new LineSegment(Selection.Points.Last(), true));
            }

            InvalidateVisual();
        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            drawingContext.DrawGeometry(_fillBrush, _strokePen, Selection.SelectionGeometry);
            base.OnRender(drawingContext);
        }

    }
}
